package com.gitee.wsl.compose.modifier.animate

import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.rotate

// Modifier 扩展函数中不使用 `this` 接收者，就需要加上这个注解
fun Modifier.rotateOnClick(): Modifier = composed {
    // 是否旋转
    var isRotating by remember { mutableStateOf(false) }

    // 创建无限旋转的动画
    val infiniteTransition = rememberInfiniteTransition(label = "rotateOnHover")

    // 初始值和目标值
    val initialValue = 0f
    val targetValue = if (isRotating) 360f else 0f

    // 旋转角度
    val rotation by infiniteTransition.animateFloat(
        initialValue = initialValue,
        targetValue = targetValue,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 3000, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        ),
        label = "rotation"
    )


    // 应用点击事件和旋转效果
    clickable {
        isRotating = !isRotating
    }.rotate(rotation)
}


//Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
//    Box(
//        Modifier
//            .size(100.dp)
//            .rotateOnClick()
//            .background(Color.Green)
//    )
//}
